/*
 * @Author: hongbin
 * @Date: 2021-12-20 19:36:25
 * @LastEditors: hongbin
 * @LastEditTime: 2021-12-20 21:45:42
 * @Description:聚合数据查询天气接口
 */
const request = require('request');
const key = "676a0b92a4dbce1cf90b54e2c34b40ee";
const url = (city) => `http://apis.juhe.cn/simpleWeather/query?key=${key}&city=${city}`;

const queryWeather = (req, res) => {
    // city 传来的就是转码过的
    const { city } = req.query;
    console.log(city);
    if (!city) {
        return res.json("请输入有效城市名");
    }
    // if (city.match(/^[\u4e00-\u9fa5]$/)) {
    //     return res.json("请输入中文名的城市");
    // }
    request(url(city), (err, response, body) => {
        if (!err && response.statusCode == 200) {
            const payload = JSON.parse(body);
            console.log("请求成功", payload);
            // 如果不支持地址
            if (!payload.result) {
                return res.json(payload.reason);
            }
            // 拼接结果
            const { result: { city: City, realtime: { info: weather, direct, power, aqi }, future } } = payload;
            let info = `${City}今日天气：${weather} ${(direct && power) ? `风向${direct}风力${power}` : ""}${power} ${aqi ? "空气质量指数" + aqi : ""}|未来5天天气情况：|`;

            future.forEach(({ date, temperature, weather, direct }) => {
                const str = `${date} ${temperature} ${weather} ${direct}|`;
                info += str;
            });
            console.log(info);
            return res.json(info);
        } else {
            return res.json("抱歉查询失败，每日只能查询50次或请求错误");
        }
    })
}

module.exports = {
    queryWeather
}